package com.aifast.crm.customer.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import com.aifast.common.base.BaseEntity;
import com.aifast.common.base.R;
import com.aifast.common.dataScope.DataScope;
import com.aifast.common.global.Const;
import com.aifast.common.layui.LayuiDataTable;
import com.aifast.common.layui.LayuiPageFactory;
import com.aifast.common.util.AiUtil;
import com.aifast.common.util.EasyExcelUtil;
import com.aifast.crm.customer.dao.CrmCustomerDao;
import com.aifast.crm.customer.entity.CrmCustomer;
import com.aifast.system.sys.dao.SysUserDao;
import com.aifast.system.sys.entity.SysUser;
import com.aifast.system.sys.entity.UserInfo;
import com.aifast.system.sys.service.SysOrgService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户信息Service业务层处理
 *
 * @author fujian
 * @date 2022-08-24
 */
@Service
@RequiredArgsConstructor
public class CrmCustomerService extends ServiceImpl<CrmCustomerDao, CrmCustomer> {
    private final CrmCustomerDao dao;
    private final SysUserDao userDao;
    private final SysOrgService orgService;

    /**
     * layui数据表格列表查询方法
     * <br>这里参数不使用参数类，当超过5个参数时筛选条件参数建议使用参数类param封装
     *
     * @param page 分页
     * @return 列表数据
     */
    @DataScope
    public LayuiDataTable list(CrmCustomer pm, Page page) {
        return LayuiPageFactory.init(page(page, dao.select(pm)));
    }


    /**
     * 新增或者修改
     * <br>vo的方法另写，里面有判定是否新增还是修改 可自定义逻辑
     *
     * @param crmCustomer
     * @return
     */
    @Transactional
    public Boolean insertOrUpdate(CrmCustomer crmCustomer) {
        if (ObjectUtil.isNull(crmCustomer.getId())) {
            crmCustomer.setBelongUser(UserInfo.get().getUserId().toString());
            crmCustomer.setOrgId(UserInfo.get().getOrgId());
        }
        return saveOrUpdate(crmCustomer);
    }

    /**
     * 批量设置相关团队人员
     *
     * @param customerId 客户id
     * @param userIds    用户id
     * @return
     */
    @Transactional
    public Boolean addTeamMember(Integer customerId, String userIds) {
        if (ObjectUtil.isNull(customerId) || StrUtil.isBlank(userIds)) {
            return false;
        }
        CrmCustomer customer = getById(customerId);
        customer.setBelongUser(StrUtil.join(Const.SYMBOL_COMMA, customer.getBelongUser(), userIds));
        return updateById(customer);
    }

    /**
     * 删除团队成员
     *
     * @param customerId 客户id
     * @param userIds    用户id
     * @return
     */
    public Boolean delTeamMember(Integer customerId, String userIds) {
        if (ObjectUtil.isNull(customerId) || StrUtil.isBlank(userIds)) {
            return false;
        }
        CrmCustomer customer = getById(customerId);
        List<String> main = Convert.toList(String.class, customer.getBelongUser().split(Const.SYMBOL_COMMA));
        List<String> tmp = Convert.toList(String.class, userIds.split(Const.SYMBOL_COMMA));
        /*主要负责人不能删除*/
        tmp.remove(main.get(0));

        main.removeAll(tmp);
        String collect = main.stream().collect(Collectors.joining(Const.SYMBOL_COMMA));
        customer.setBelongUser(collect);
        return updateById(customer);
    }

    /**
     * 获取团队成员
     *
     * @param customerId 客户id
     * @return
     */
    public List<Map<String, Object>> getTeamMember(Integer customerId) {
        CrmCustomer customer = getById(customerId);
        List<Integer> integers = Convert.toList(Integer.class, customer.getBelongUser().split(Const.SYMBOL_COMMA));
        List<Map<String, Object>> sysUsers = userDao.selectMaps(new LambdaQueryWrapper<SysUser>().select(BaseEntity::getId, SysUser::getRealName, SysUser::getOrgId).in(BaseEntity::getId, integers));
        sysUsers.stream().forEach(i -> {
            if (ObjectUtil.equal(integers.get(0), Convert.toInt(i.get("id")))) {
                i.put("mainRole", "主要负责人");
            } else {
                i.put("mainRole", "成员");
            }
            i.put("permDesc", "读写");
            i.put("realName", i.get("real_name"));
//            i.put("orgName", Optional.ofNullable(orgService.info(Convert.toInt(i.get("org_id")))).get().getName());
        });

        return sysUsers;
    }

    /**
     * 删除方法
     * <br>提供单个删除和批量删除
     *
     * @param id  数据id
     * @param ids 数据id集合
     * @return
     */
    public Boolean del(Long id, String ids) {
        List<Long> list = new ArrayList<>();
        if (StrUtil.isNotBlank(ids)) {
            list = Convert.toList(Long.class, ids.split(","));
        }
        if (ObjectUtil.isNotNull(id)) {
            list.add(id);
        }
        try {
            list.forEach(i -> { update(new UpdateWrapper<CrmCustomer>().set("deleted", true).eq("id", i)); });
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 数据详情
     *
     * @param id 数据id
     * @return
     */
    public R info(Long id) {
        if (ObjectUtil.isNull(id)) return R.ERROR();
        CrmCustomer one = getById(id);
        return R.OK(one);
    }


    @DataScope
    public void export(CrmCustomer crmCustomer, HttpServletResponse response) {
        Page page = page(AiUtil.getExportPage(), dao.select(crmCustomer));
        try {
            EasyExcelUtil.export("客户","",CrmCustomer.class,page.getRecords(),response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
